package com.foxchen.textinputapp.config;

import cn.dev33.satoken.exception.NotLoginException;
import com.foxchen.textinputapp.common.ResponseBean;
import com.foxchen.textinputapp.exception.BaseException;
import com.foxchen.textinputapp.utils.I18nUti;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.List;

@Slf4j
@ControllerAdvice
public class GlobalExceptionConfig {
    @ExceptionHandler(NotLoginException.class)
    public ResponseEntity<ResponseBean<?>> handleNotLoginException(NotLoginException e) {
        log.error("api execute exception error",e);
        String errorMsg = I18nUti.getStrByKey("user.status.not.login");
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ResponseBean.error(errorMsg));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseBean<?>> handleException(Exception e) {
        log.error("api execute exception error",e);
        String errorMsg = I18nUti.getStrByKey("server.error");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseBean.error(errorMsg));
    }

    @ExceptionHandler(BaseException.class)
    public ResponseEntity<ResponseBean<?>> handleBaseException(BaseException e) {
        log.error("api execute base exception error",e);
        return ResponseEntity.status(HttpStatus.OK).body(ResponseBean.error(e.getMessage()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ResponseBean<?>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("api execute method argument not valid exception error",e);
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if(CollectionUtils.isEmpty(fieldErrors)){
            return handleException(e);
        }

        FieldError first = fieldErrors.get(0);
        String errorKey = first.getDefaultMessage();

        String errorMsg = I18nUti.getStrByKey(errorKey);
        return ResponseEntity.status(HttpStatus.OK).body(ResponseBean.error(errorMsg));
    }
}
